import {
  HEAD_THEME_VAR_NAME,
  LOCAL_STORAGE_KEYS,
  PROJECT_PREFIX,
  THEME_VAR,
} from '../../../types/constants'
import { ThemeSourceMode, ThemeType } from '../../../types/interfaces'

/**
 * 主题管理工具类
 */
export class ThemeUtils {
  /**
   * 检查当前是否为深色模式
   */
  static isDarkMode(): boolean {
    return this.getCurrentTheme() === ThemeType.DARK
  }

  /**
   * 设置当前主题
   */
  static setTheme(theme?: ThemeType): void {
    document.documentElement.style.setProperty(
      HEAD_THEME_VAR_NAME,
      theme || this.getCurrentTheme(),
    )
  }

  /**
   * 获取当前主题
   */
  static getCurrentTheme(mode: ThemeSourceMode = ThemeSourceMode.LOCAL_STORAGE): ThemeType {
    switch (mode) {
      case ThemeSourceMode.INLINE:
        return this.getInlineTheme()
      case ThemeSourceMode.COMPUTED:
        return this.getComputedTheme()
      case ThemeSourceMode.LOCAL_STORAGE:
      default:
        return this.getStorageTheme()
    }
  }

  /**
   * 从内联样式获取主题
   */
  static getInlineTheme(): ThemeType {
    return this.extractThemeValue(document.documentElement.style.cssText)
  }

  /**
   * 从本地存储获取主题
   */
  static getStorageTheme(): ThemeType {
    return localStorage.getItem(LOCAL_STORAGE_KEYS.PageTheme) as ThemeType || ThemeType.LIGHT
  }

  /**
   * 从计算样式获取主题
   */
  static getComputedTheme(): ThemeType {
    const theme = getComputedStyle(document.documentElement)
      .getPropertyValue(THEME_VAR)
      .trim()
    return Object.values(ThemeType).includes(theme as ThemeType)
      ? theme as ThemeType
      : ThemeType.LIGHT
  }

  static extractThemeValue(styleText: string): ThemeType {
    const match = styleText.match(`--${PROJECT_PREFIX}-theme:[\\s]*(${Object.values(ThemeType).join('|')})`)
    return match?.[1] as ThemeType || ThemeType.LIGHT
  }
}
